package com.demo.spring.data.elasticsearch;

import java.util.ArrayList;
import java.util.List;

import org.elasticsearch.index.query.SimpleQueryStringBuilder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.data.elasticsearch.core.query.IndexQueryBuilder;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.alibaba.fastjson.JSON;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:elasticsearch.xml" })
public class TestElasticsearch {
	@Autowired
	private ElasticsearchTemplate elasticsearchTemplate;

	@Autowired
	private SampleElasticsearchRepository repository;

	@Test
	public void repository() {
		String documentId = "test";
		SampleEntity sampleEntity = new SampleEntity();
		sampleEntity.setId(documentId);
		sampleEntity.setMessage("some message");

		repository.save(sampleEntity);
	}

	@Test
	public void bulkIndex() {
		List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
		//first document
		String documentId = "123456";
		SampleEntity sampleEntity1 = new SampleEntity();
		sampleEntity1.setId(documentId);
		sampleEntity1.setMessage("some message");

		IndexQuery indexQuery1 = new IndexQueryBuilder().withId(sampleEntity1.getId()).withObject(sampleEntity1).build();
		indexQueries.add(indexQuery1);

		//second document
		String documentId2 = "123457";
		SampleEntity sampleEntity2 = new SampleEntity();
		sampleEntity2.setId(documentId2);
		sampleEntity2.setMessage("some message");

		IndexQuery indexQuery2 = new IndexQueryBuilder().withId(sampleEntity2.getId()).withObject(sampleEntity2).build();
		indexQueries.add(indexQuery2);

		//bulk index
		elasticsearchTemplate.bulkIndex(indexQueries);
	}

	@Test
	public void queryForPage() {
		String documentId = "123456";
		SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(queryString(documentId).field("id")).build();
		Page<SampleEntity> sampleEntities = elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class);
		print(sampleEntities.getContent());
	}
	
	void print(Object obj){
		System.out.println(JSON.toJSONString(obj));
	}

	private SimpleQueryStringBuilder queryString(String documentId) {
		SimpleQueryStringBuilder queryBuilder = new SimpleQueryStringBuilder(documentId);
		return queryBuilder;
	}
}
